<template>
  <div class="formula-f">
    <el-header style="padding: 0px;display:flex;justify-content:space-between;align-items: center">
      <div style="margin-left: 5px;margin-right: 20px;display: inline">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddEmpView">添加公式</el-button>
      </div>
    </el-header>
    <el-table :data="tableData" border v-loading="tableLoading" style="width: 100%">
      <el-table-column prop="formulaName" label="公式名称" align="center" width="180"></el-table-column>
      <el-table-column prop="formulaTypeCn" label="公式类型" align="center" width="180"></el-table-column>
      <el-table-column align="center" label="公式信息">
        <template slot-scope="scope">
          <span @click="lookThing(scope.$index)">查看</span>
        </template>
      </el-table-column>
      <el-table-column prop="formulaInfo" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            @click="showEditEmpView(scope.row)"
            style="padding: 3px 4px 3px 4px;margin: 2px"
            size="mini"
            type="warning"
          >修改</el-button>
          <el-button
            @click="deleteFormula(scope.row.formulaId)"
            style="padding: 3px 4px 3px 4px;margin: 2px"
            size="mini"
            type="danger"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-form :model="formList" :rules="rules" ref="addEmpForm" style="margin: 0px;padding: 0px;">
      <div style="text-align: left">
        <el-dialog
          :title="dialogTitle"
          style="padding: 0px;"
          @close="closeModal"
          :close-on-click-modal="false"
          :visible.sync="dialogVisible"
          width="77%"
        >
          <el-form-item label="公式名称:" prop="formulaName">
            <el-input
              prefix-icon="el-icon-edit"
              v-model="formList.formulaName"
              :disabled="dialogTitle === '修改公式'"
              size="mini"
              style="width: 180px"
              placeholder="请输入公式名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="公式类型:" prop="formulaType">
            <el-select
              v-model="formList.formulaType"
              placeholder="请选择"
              size="mini"
              @change="formulaTypeChange"
            >
              <el-option
                v-for="item in finFormulaTypeArr"
                :key="item.indexValue"
                :label="item.label"
                style="width: 120px"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <div
            v-if="formList.formulaType === 'INCOM_FROM_INVESTMENT' || formList.formulaType === ''"
          >
            <el-form-item label="公式详情:" prop="info">
              <el-input
                prefix-icon="el-icon-edit"
                v-model="formList.info.investmentFormula"
                size="mini"
                style="width: 180px"
                placeholder="请输入公式"
              ></el-input>
            </el-form-item>
            <el-row v-for="(item, index) in formList.info.profitRateList" :key="'info4-'+index">
              <el-col :span="12">一期：受让资产总额：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.condition"
                  size="mini"
                  style="width: 140px"
                ></el-input>
              </el-col>
              <el-col :span="8">预期收益率：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.profitRate"
                  size="mini"
                  style="width: 140px"
                ></el-input>
              </el-col>
            </el-row>
          </div>
          <div v-if="formList.formulaType === 'INCOM_FROM_INVESTMENT_1_X'">
            <el-form-item label="公式详情:" prop="info">
              <el-input
                prefix-icon="el-icon-edit"
                v-model="formList.info[0].investmentFormula"
                size="mini"
                style="width: 180px"
                placeholder="请输入第一期公式"
              ></el-input>
              <el-input
                prefix-icon="el-icon-edit"
                v-model="formList.info[1].investmentFormula"
                size="mini"
                style="width: 180px"
                placeholder="请输入第二期公式"
              ></el-input>
              <el-input
                prefix-icon="el-icon-edit"
                v-model="formList.info[2].investmentFormula"
                size="mini"
                style="width: 180px"
                placeholder="请输入第三期公式"
              ></el-input>
              <el-input
                prefix-icon="el-icon-edit"
                v-model="formList.info[3].investmentFormula"
                size="mini"
                style="width: 180px"
                placeholder="请输入第四期公式"
              ></el-input>
            </el-form-item>
            <el-row v-for="(item, index) in formList.info[0].profitRateList" :key="'info3-'+index">
              <el-col :span="12">一期：受让资产总额：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.condition"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第一期受让资产总额"
                ></el-input>
              </el-col>
              <el-col :span="8">预期收益率：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.profitRate"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第一期收益率"
                ></el-input>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in formList.info[1].profitRateList" :key="'info2-'+index">
              <el-col :span="12">二期：受让资产总额：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.condition"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第二期受让资产总额"
                ></el-input>
              </el-col>
              <el-col :span="8">预期收益率：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.profitRate"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第二期收益率"
                ></el-input>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in formList.info[2].profitRateList" :key="'info1-'+index">
              <el-col :span="12">三期：受让资产总额：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.condition"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第三期受让资产总额"
                ></el-input>
              </el-col>
              <el-col :span="8">预期收益率：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.profitRate"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第三期收益率"
                ></el-input>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in formList.info[3].profitRateList" :key="'info0-'+index">
              <el-col :span="12">四期：受让资产总额：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.condition"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第四期受让资产总额"
                ></el-input>
              </el-col>
              <el-col :span="8">预期收益率：
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.profitRate"
                  size="mini"
                  style="width: 140px"
                  placeholder="请输入第四期收益率"
                ></el-input>
              </el-col>
            </el-row>
          </div>
          <el-row>
            <el-col :span="20">&nbsp;</el-col>
            <el-col :span="4">
              <el-button size="mini" type="primary" @click="deleteParams()">删 除</el-button>
              <el-button size="mini" type="primary" @click="addParams()">添 加</el-button>
            </el-col>
          </el-row>
          <el-row>
            <div></div>
            <div
              v-for="(item, index) in formulaParams"
              :key="'info3-'+index"
              v-show="formulaParams[index].value !== '资产预期年化收益率'"
            >
              <el-col :span="6">
                {{item.key}}:
                <el-input
                  prefix-icon="el-icon-edit"
                  v-model="item.label"
                  size="mini"
                  style="width: 140px"
                  :placeholder="item.value"
                ></el-input>
              </el-col>
            </div>
          </el-row>
          <el-form-item label="公式试算(必须试算成功才能提交):" prop="formulaType">
            <el-button size="mini" type="primary" @click="testFormula()">试 算</el-button>
            <el-input
              prefix-icon="el-icon-edit"
              v-model="formulaResult"
              size="mini"
              disabled
              style="width: 140px"
            ></el-input>
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click.native="addEmp('addEmpForm')">确 定</el-button>
            <el-button size="mini" @click="cancelEidt">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </el-form>
    <div style="display: flex;justify-content: center;margin: 40px 0">
      <el-pagination
        background
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="currentChange"
        layout="prev, pager, next"
        :total="totalCount"
      ></el-pagination>
    </div>
    <div style="margin:30px 0;" class="fw tc">共{{Math.ceil(totalCount/pageSize)}}页,{{totalCount}}条信息</div>
    <el-dialog title="预期收益公式" :visible.sync="dialogSaleShow">
      <el-table :data="gridData" border>
        <el-table-column property="money" label="受让资产总额（万元）"></el-table-column>
        <el-table-column label="资产预期年化一期收益率（%/年）">
          <template slot-scope="scope">{{ scope.row.year }}%</template>
        </el-table-column>
      </el-table>
      <el-table :data="gridData2" border v-if="gridData2.length >= 1">
        <el-table-column property="money" label="受让资产总额（万元）"></el-table-column>
        <el-table-column label="资产预期年化二期收益率（%/年）">
          <template slot-scope="scope">{{ scope.row.year }}%</template>
        </el-table-column>
      </el-table>
      <el-table :data="gridData3" border v-if="gridData3.length >= 1">
        <el-table-column property="money" label="受让资产总额（万元）"></el-table-column>
        <el-table-column label="资产预期年化三期收益率（%/年）">
          <template slot-scope="scope">{{ scope.row.year }}%</template>
        </el-table-column>
      </el-table>
      <el-table :data="gridData4" border v-if="gridData4.length >= 1">
        <el-table-column property="money" label="受让资产总额（万元）"></el-table-column>
        <el-table-column label="资产预期年化四期收益率（%/年）">
          <template slot-scope="scope">{{ scope.row.year }}%</template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      pageSize: 10,
      currentPage: 1,
      totalCount: 1,
      tableData: [],
      tableLoading: false,
      dialogVisible: false,
      dialogSaleShow: false,
      dialogTitle: "",
      gridData: [],
      gridData2: [],
      gridData3: [],
      gridData4: [],
      formList: {
        formulaName: "",
        formulaType: "",
        info: [
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          }
        ]
      },
      finFormulaTypeArr: [],
      rules: {
        formulaName: [
          { required: true, message: "必填:公式名称", trigger: "blur" }
        ],
        formulaType: [
          { required: true, message: "必填:公式类型", trigger: "change" }
        ],
        info: [{ required: true, message: "必填:公式详情", trigger: "blur" }]
      },
      formulaParams: [],
      formulaResult: ""
    };
  },
  mounted() {
    this.getList();
    this.getRequest("/formula/riskerFormulaType").then(resp => {
      if (resp && resp.status == 200) {
        resp.data.obj.forEach((v, i) => {
          this.finFormulaTypeArr.push({
            label: v.formuTypeCn,
            value: v.formuType,
            realValue: v.remark,
            indexValue: v.formuTypeCn
          });
        });
      }
    });
  },
  methods: {
    lookThing(index) {
      this.dialogSaleShow = true;
      this.gridData = [];
      this.gridData2 = [];
      this.gridData3 = [];
      this.gridData4 = [];
      let result = JSON.parse(this.tableData[index].formulaInfo);
      if (!(result.formulaType.indexOf("_1_X") > -1)) {
        result.formulaInfo.profitRateList.forEach((v, i) => {
          this.gridData.push({
            money: v.condition,
            year: v.profitRate
          });
        });
      } else {
        result.formulaList.forEach((item, idx) => {
          if (idx === 0) {
            item.profitRateList.forEach((v, i) => {
              this.gridData.push({
                money: v.condition,
                year: v.profitRate
              });
            });
          } else if(idx === 1){
            item.profitRateList.forEach((v, i) => {
              this.gridData2.push({
                money: v.condition,
                year: v.profitRate
              });
            });
          }else if(idx === 2){
            item.profitRateList.forEach((v, i) => {
              this.gridData3.push({
                money: v.condition,
                year: v.profitRate
              });
            });
          }else if(idx === 3){
            item.profitRateList.forEach((v, i) => {
              this.gridData4.push({
                money: v.condition,
                year: v.profitRate
              });
            });
          }
        });
      }
    },
    getList() {
      this.tableLoading = true;
      this.getRequest(
        "/formula/risker/list?pageIndex=" +
          this.currentPage +
          "&pageSize=" +
          this.pageSize
      ).then(resp => {
        if (resp && resp.status == 200) {
          this.tableData = resp.data.obj.rows;
          this.tableData.forEach((v, i) => {
            this.tableLoading = false;
            let temp = JSON.parse(v.formulaInfo);
            this.tableData[i].info = temp.formulaInfo;
            this.totalCount = resp.data.obj.total;
          });
        }
      });
    },
    currentChange(currentChange) {
      this.currentPage = currentChange;
      this.getList();
    },
    showAddEmpView() {
      this.dialogTitle = "添加公式";
      this.dialogVisible = true;
    },
    async showEditEmpView(row) {  
      this.dialogTitle = "修改公式";
      this.dialogVisible = true;
      this.formulaParams = [];
      Object.assign(this.formList, row);  
      if (this.formList.formulaType === "INCOM_FROM_INVESTMENT") {
        this.formList.info = [];
        this.formList.info = JSON.parse(
          this.formList.formulaInfo
        ).formulaInfo;
      } else if (this.formList.formulaType === "INCOM_FROM_INVESTMENT_1_X") {
        this.formList.info = JSON.parse(this.formList.formulaInfo).formulaList;
      }
      console.log(this.formList.info)
      //如果只有2期的产品，则加上三期和四期的信息，内容为空
      if(this.formList.info.length==2){
        var obj1={investmentFormula: "",profitRateList:[]}
        for(let i=0;i<this.formList.info[0].profitRateList.length;i++){
          obj1.profitRateList.push({condition: "",profitRate: ""});
        }
        this.formList.info.push(obj1)
        var obj2={investmentFormula: "",profitRateList:[]}
        for(let i=0;i<this.formList.info[0].profitRateList.length;i++){
          obj2.profitRateList.push({condition: "",profitRate: ""});
        }
        this.formList.info.push(obj2)
      }else if(this.formList.info.length==3){  //如果只有3期的产品，则加上四期的信息，内容为空
        var obj1={investmentFormula: "",profitRateList:[]}
        for(let i=0;i<this.formList.info[0].profitRateList.length;i++){
          obj1.profitRateList.push({condition: "",profitRate: ""});
        }
        this.formList.info.push(obj1)
      }
      this.finFormulaTypeArr.forEach((v, i) => {
        if (v.value === this.formList.formulaType) {
          let remarkTemp = JSON.parse(v.realValue);
          for (let i in remarkTemp) {
            this.formulaParams.push({
              key: i,
              value: remarkTemp[i],
              label: ""
            });
          }
        }
      });
    },
    closeModal() {
      this.dialogVisible = false;
      this.emptyEmpData();
    },
    emptyEmpData() {
      this.formList = {
        formulaName: "",
        formulaType: "",
        info: [
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          }
        ]
      };
      this.formulaParams = [];
      this.formulaResult=""
    },
    formulaTypeChange(val) {
      this.formulaParams = [];
      if (val === "INCOM_FROM_INVESTMENT_1_X") {
        this.formList.info = [
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
          {
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]
          },
        ];
      } else if (val === "INCOM_FROM_INVESTMENT") {
        this.formList.info = {
          
            investmentFormula: "",
            profitRateList: [
              {
                condition: "",
                profitRate: ""
              }
            ]       
        };
      }
      this.finFormulaTypeArr.forEach((v, i) => {
        if (v.value === val) {
          let remarkTemp = JSON.parse(v.realValue);
          for (let i in remarkTemp) {
            this.formulaParams.push({
              key: i,
              value: remarkTemp[i],
              label: ""
            });
          }
        }
      });
    },
    addParams() {
      if (
        this.formList.formulaType === "INCOM_FROM_INVESTMENT" 
      ) {
          this.formList.info.profitRateList.push({
            condition: "",
            profitRate: ""
          });
      } else if (this.formList.formulaType === "INCOM_FROM_INVESTMENT_1_X") {
        this.formList.info.forEach(item => {
          item.profitRateList.push({
            condition: "",
            profitRate: ""
          });
        });
      }else if(this.formList.formulaType === ""){
        this.common.showToast("info","请先选择公式类型")
      }
    },
    deleteParams() {
      if (this.formList.formulaType === "INCOM_FROM_INVESTMENT") {
        this.formList.info.profitRateList.pop({
          condition: "",
          profitRate: ""
        });
      } else if (this.formList.formulaType === "INCOM_FROM_INVESTMENT_1_X") {
        this.formList.info.forEach(item => {
          item.profitRateList.pop({
            condition: "",
            profitRate: ""
          });
        });
      }
    },
    cancelEidt() {
      this.dialogVisible = false;
      this.emptyEmpData();
    },
    testFormula() {
      let parm = {};
      this.formulaParams.forEach((v, i) => {
        if (!v.label) {
          parm[v.key] = "";
        } else {
          parm[v.key] = +v.label;
        }
      });
      let data = "";
      if (this.formList.formulaType === "INCOM_FROM_INVESTMENT") {
        data = JSON.stringify({
          formulaInfo: this.formList.info,
          formulaType: this.formList.formulaType,
          parm
        });
      } else if (this.formList.formulaType === "INCOM_FROM_INVESTMENT_1_X") {
        data = JSON.stringify({
          formulaList: this.formList.info,
          formulaType: this.formList.formulaType,
          parm
        });
      }

      this.postRequest("/formula/trialFormula", { json: data }).then(resp => {
        if (resp && resp.status == 200) {
          this.formulaResult = resp.data.obj.result;
          this.$message({
            showClose: true,
            message: resp.data.msg,
            type: "success"
          });
        }
      });
    },
    addEmp(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formulaType = this.formList.formulaType;
          let parm = {};
          this.formulaParams.forEach((v, i) => {
            if (!v.label) {
              parm[v.key] = "";
            } else {
              parm[v.key] = +v.label;
            }
          });
          let data = "";
          if (this.formList.formulaType === "INCOM_FROM_INVESTMENT") {
            data = JSON.stringify({
              formulaInfo: this.formList.info,
              formulaType: this.formList.formulaType,
              parm
            });
          } else if (
            this.formList.formulaType === "INCOM_FROM_INVESTMENT_1_X"
          ) {
            if(this.formList.info[2] && this.formList.info[2].profitRateList[0].condition==''){
              this.formList.info=this.formList.info.splice(0,2)
              console.log(this.formList.info)
            }
            data = JSON.stringify({
              formulaList: this.formList.info,
              formulaType: this.formList.formulaType,
              parm
            });
          }

          let data2 = {
            formulaName: this.formList.formulaName,
            formulaInfo: data,
            formulaType
          };
          this.postRequest("/formula/trialFormula", { json: data }).then(
            resp => {
              if (resp && resp.status == 200) {
                if (this.formList.formulaId) {
                  this.putRequest("/formula/updateFormula", {
                    formulaId: this.formList.formulaId,
                    ...data2
                  }).then(resp => {
                    if (resp && resp.status == 200) {
                      this.dialogVisible = false;
                      this.emptyEmpData();
                      this.getList();
                      this.$message({
                        showClose: true,
                        message: resp.data.msg,
                        type: "success"
                      });
                    }
                  });
                } else {
                  this.putRequest("/formula/risker/insertFormula", data2).then(
                    resp => {
                      if (resp && resp.status == 200) {
                        this.dialogVisible = false;
                        this.emptyEmpData();
                        this.getList();
                        this.$message({
                          showClose: true,
                          message: resp.data.msg,
                          type: "success"
                        });
                      }
                    }
                  );
                }
              }
            }
          );
        } else {
          return false;
        }
      });
    },
    deleteFormula(id) {
      this.$confirm("此操作将永久删除该公式, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteRequest("/formula/" + id).then(resp => {
            if (resp && resp.data.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            }
          }); 
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style scoped>
.formula-f .el-row {
  margin-bottom: 20px;
}
.el-dialog__body .el-table {
  margin-bottom: 10px;
}
/deep/ .el-input.is-disabled .el-input__inner{
  color: #000;
}
</style>
